package com.lightsh.object;

import java.util.ArrayList;

import org.jbox2d.common.Vec2;

import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;

import com.lightsh.gui.BaseScreen;
import com.lightsh.interfaces.creator.IBodyCreator;
import com.lightsh.utility.GeometryUtility;
import com.lightsh.utility.Utility;

public abstract class PolygonObject extends SimpleObject{
	
	protected ArrayList<Vec2> mPolygonVertexs;
	protected float[] mVertices;
	protected Path mPath;
	
	public PolygonObject(BaseScreen screen, float x, float y) {
		super(screen, x, y);
		mPolygonVertexs = new ArrayList<Vec2>();
		mPath = new Path();
	}

	@Override
	public void draw(Canvas canvas, Rect screenRect, float selfScale, float worldScale) {
		if(!isInRect(screenRect, selfScale)){
			return;
		}
		Vec2 vec2 = getPosition();
		canvas.save();
		rotateCanvas(canvas, mAngle, vec2, screenRect, selfScale, worldScale);
		if(mSprite != null){
			mSprite.draw(canvas, mPaint, (int)((vec2.x ) / selfScale + mDrawImageOffsetX - screenRect.left), (int)((vec2.y) / selfScale + mDrawImageOffsetY- screenRect.top), worldScale);
		}else if(mBitmap != null){
			drawBitmap(canvas, vec2.x, vec2.y, screenRect, selfScale, worldScale);
		}else{
			GeometryUtility.trackPolygonPath(mPath, vec2, mPolygonVertexs, mVertices, selfScale, worldScale, screenRect.left, screenRect.top);
			canvas.drawPath(mPath, mPaint);
		}		
		canvas.restore();
		
	}
	
	/**
	 * 需严格按顺时针依次添加，并且不能时凹形。
	 * <br/>注意，这里所添加的顶点的值，以position为参照物，即以所设置的 x, y 值作为坐标系的原点(0, 0))
	 * <br/>这些节点需要在{@link IBodyCreator#create()}调用之前完成添加
	 * <br/>
	 * <br/>例如下图， '。'为本Polygon所设置的x,y坐标,而三个'.'分别代边三角形的三个顶点,其中上顶点的坐标应该为(1，0)，假定该顶点与'。'水平并且向右偏移1的距离。
	 * <br/>	---------------------------------
	 * <br/>	|      。  .	            |
	 * <br/>	|                       |
	 * <br/>	|      .      .	        |
	 * <br/>	|                       |
	 * <br/>	----------------------------------
	 * 
	 * @param vec2 点向量
	 */
	public void add(Vec2 vec2) {
		mPolygonVertexs.add(vec2);
	}
	
	@Override
	public boolean isInRect(Rect rect, float selfScale) {
		Vec2 centerPoint = getPosition();
		return GeometryUtility.isPolygonInRect(centerPoint, mPolygonVertexs, rect, selfScale);
	}

	@Override
	public boolean isPointInside(Vec2 point, float worldScale, float screenX, float screenY) {
		return GeometryUtility.isPointInPolygon(getPosition(), mPolygonVertexs, worldScale, screenX, screenY, point);
	}

	@Override
	public void create() {
		super.create();
		mVertices = new float[mPolygonVertexs.size() << 1];
	}
	
	
}
